package com.djk.daily.thread.threadobjectclasscommonmethods;

/**
 * @Description 证明wait只释放当前的那把锁
 * @Author dujunkai
 * @Date 2021/7/3 20:54
 **/
public class WaitNotifyReleaseOwnMonitor2 {
    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {

            synchronized (resourceA) {

                System.out.println("ThreadA got resourceA lock.");

                synchronized (resourceB) {

                    System.out.println("ThreadA got resourceB lock.");

                    try {

                        resourceA.wait();

                        System.out.println("ThreadA releases resourceA lock.");

                        resourceA.notify();//将resourceA替换位resourceB无法唤醒Thread1

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }

        });




        Thread thread2 = new Thread(() -> {

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            synchronized (resourceA) {

                System.out.println("ThreadB got resourceA lock.");

                System.out.println("ThreadB tries to resourceB lock.");

                resourceA.notify();

                try {

                    resourceA.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println("--------");

                synchronized (resourceB) {

                    System.out.println("ThreadB got resourceB lock.");

                }

            }

        });

        thread1.start();
        thread2.start();
    }
}
